<?php
/*TODO: VERIFICACOES E TESTES E GERALMENTE DUMMY PROOFING, TB RETORNAR JSON E XML*/
	session_start();
	
		/*verificacoes parametros*/
	if(isset($_REQUEST['xml']) && ($_REQUEST['xml'] == '1')){
		$xml=1;
	}else{$xml=0;}
	
	if(session_is_registered(username)){
		$name=$_SESSION['username'];
	}
	else{
		//header("refresh:3; url=../../home.html");
		//echo "You need to be logged in to access this page - redirecting in 3 seconds...";
		 if($xml==0){
			$error['Result'] = array('AddLink'=>'notLoggedInError');
			echo json_encode($error);
			die;
		}else{
			$doc = new DomDocument('1.0');
			// create root node
			$root = $doc->createElement('Result');
			$root = $doc->appendChild($root);
			$attr = $doc->createAttribute("xmlns:xsi");
			$attr->value = "http://www.w3.org/2001/XMLSchema-instance";
			$root->appendChild($attr);
			$attr = $doc->createAttribute("xsi:noNamespaceSchemaLocation");
			$attr->value = "http://gnomo.fe.up.pt/~ei10048/trabalho2/xsd.xsd";
			$root->appendChild($attr);
			//childs of root
			$error = $doc->createElement('AddLink');
			$error= $root->appendChild($error);
			$value = $doc->createTextNode('notLoggedInError');
			$value = $error->appendChild($value);
			echo $doc->saveXML();
		}
		die;
	}
	/*verificacao de erros*/
	//$error -> urlError
	
	$verbose = $_REQUEST['verbose'];
	/*add_links (&url={url}, &tag_list={tag_1,tag_2,...,tag_n}, &shared=yes, &xml=0, &verbose=1, &title, &description*/
	/*[caminho]/addl_link.php?&url="www.google.pt"[&tag=tag1,tag2,tag3&shared=yes&xml=1&title=title&description=description]*/
	if($verbose == 1){ echo ("parameters echo:");}
	

	
	if(isset($_REQUEST['url']) && $_REQUEST['url'] != ""){
		$url=strtolower($_REQUEST['url']);
		if($verbose == 1){ echo ("url:".$url."|");}
		
		if(isset($_REQUEST['title']) && $_REQUEST['title'] != ""){
			$title=$_REQUEST['title'];
		}else{$title="";}
		if($verbose == 1){ echo ("title:".$title."|");}
		
		if(isset($_REQUEST['description']) && $_REQUEST['description'] != ""){
			$description=$_REQUEST['description'];
		}else{$description="";}
		if($verbose == 1){ echo ("description:".$description."|");}
		
		if(isset($_REQUEST['tag_list']) && $_REQUEST['tag_list'] != ""){
			$tag_list=split (',', $_REQUEST['tag_list']);
		}else{$tag_list="";}
		if($verbose == 1){ echo ($tag_list . '<br />');}
		if(isset($_REQUEST['shared']) && (($_REQUEST['shared'] == 'yes')||($_REQUEST['shared'] == 0))){
			$shared=0;
		}else{$shared=1;}
		if($verbose == 1){ echo ("shared:".$shared."<br />");}
	}
	else{
		if($verbose == 1){echo "invalid parameters, try again";}
		if($xml == 0){
			$error['Result'] = array('AddLink'=>'noUrlError');
			echo json_encode($error);
		}
		else{
			$doc = new DomDocument('1.0');
			$doc->formatOutput = TRUE;
			// create root node
			$root = $doc->createElement('Result');
			$root = $doc->appendChild($root);
			$attr = $doc->createAttribute("xmlns:xsi");
			$attr->value = "http://www.w3.org/2001/XMLSchema-instance";
			$root->appendChild($attr);
			$attr = $doc->createAttribute("xsi:noNamespaceSchemaLocation");
			$attr->value = "http://gnomo.fe.up.pt/~ei10048/trabalho2/xsd.xsd";
			$root->appendChild($attr);
			//childs of root
			$error = $doc->createElement('AddLink');
			$error= $root->appendChild($error);
			$value = $doc->createTextNode('noUrlError');
			$value = $error->appendChild($value);
			echo $doc->saveXML();
		}
		die;
	}
	if($verbose == 1){ echo ($xml . '<br />');}
	if($verbose == 1){ echo ("parameters echo end" . '<br />');}
	try{
		$db = new PDO('sqlite:../../projecto1.db');
	}
	catch(PDOException $err){
		if($verbose==1){echo "cannot access database";}
		if($xml==0){
			$error['Result'] = array('AddLink'=>'DatabaseError');
			echo json_encode($error);
			die;
		}else{
			$doc = new DomDocument('1.0');
			$doc->formatOutput = TRUE;
			// create root node
			$root = $doc->createElement('Result');
			$root = $doc->appendChild($root);
			$attr = $doc->createAttribute("xmlns:xsi");
			$attr->value = "http://www.w3.org/2001/XMLSchema-instance";
			$root->appendChild($attr);
			$attr = $doc->createAttribute("xsi:noNamespaceSchemaLocation");
			$attr->value = "http://gnomo.fe.up.pt/~ei10048/trabalho2/xsd.xsd";
			$root->appendChild($attr);
			//childs of root
			$error = $doc->createElement('AddLink');
			$error= $root->appendChild($error);
			$value = $doc->createTextNode('DatabaseError');
			$value = $error->appendChild($value);
			echo $doc->saveXML();
		}
		die;
	}
	
	/*inserts the link in Link------------------------------------------------------------*/
	
	/*verifica se o link ja existe na BD*/
	$stmt = $db->prepare('SELECT idLink FROM Link WHERE linkURL=:url');
	$stmt->bindParam(':url', $url);
	$stmt->execute();
	$bd_url = $stmt->fetch();
	if(!$bd_url){/*url still doesn't exist in the DB*/
		if(strpos($url, '://') === false)
		$url = 'http://' . $url;
	
		$stmt = $db->prepare('INSERT INTO Link values (NULL, :url,0)');
		$stmt->bindParam(':url', $url, PDO::PARAM_STR);
		$stmt->execute();
		
		$stmt = $db->prepare('SELECT idLink FROM Link WHERE linkURL=:url');
		$stmt->bindParam(':url', $url);
		$stmt->execute();
		$link_id=$stmt->fetch();
		$link_id=$link_id[0];
	}/*if it exists already, we update existing values in User_Link*/
	
	/*associates user to link--------------------------------------------------------------*/
	
	/*link--------------------------------------------------------------------------------*/
	
	/*$*/
	else{$link_id=$bd_url[0];}
	
	if($verbose == 1){ echo ('<br />'."LINK_ID: " . $link_id . '<br />');}
	
	/*user----------------------------------------------------------------------------*/
	$stmt = $db->prepare('SELECT idUser FROM User WHERE User.userName=:name');
	$stmt->bindParam(':name', $name);
	$stmt->execute();
	$user_id = $stmt->fetch();/*cannot be null*/
	$user_id=$user_id['idUser'];
	if($verbose == 1){ echo ("USER_ID: " . $user_id . '<br />');}
	/*user_link-------------------------------------------------------------------------*/
	$stmt = $db->prepare('SELECT * FROM User_Link WHERE idUser=:userId AND idLink=:linkId');
	$stmt->bindParam(':userId', $user_id);
	$stmt->bindParam(':linkId', $link_id);
	$stmt->execute();
	$bd_user_link = $stmt->fetch();
	if($verbose==1){echo '    RAGEEEEEEE:';print_r($bd_user_link);echo'<br />';}
	if(!$bd_user_link){/*if it doesn't exist yet, insert*/
		$stmt = $db->prepare('INSERT INTO User_Link values 
		(NULL, :user_id, :link_id, :shared, 
		 :description, :title)');
		$stmt->bindParam(':user_id', $user_id);
		$stmt->bindParam(':link_id', $link_id);
		$stmt->bindParam(':shared', $shared);
		$stmt->bindParam(':description', $description);
		$stmt->bindParam(':title', $title);
		$stmt->execute();
		
		/*gets adequate idUserLink id*/
		$stmt = $db->prepare('SELECT * FROM User_Link WHERE idUser=:userId AND idLink=:linkId');
		$stmt->bindParam(':userId', $user_id);
		$stmt->bindParam(':linkId', $link_id);
		$stmt->execute();
		$user_link_id = $stmt->fetch();/*cannot be null*/
		$user_link_id=$user_link_id['idUserLink'];
		if($verbose == 1){ echo ("USER_LINK_ID: " . $user_link_id . '<br />');}
	}
	else{/*if it exists already, update existing values*/		
		if($shared == '')
			$shared = $bd_user_link['shared'];	
		if($title == '')
			$title = $bd_user_link['title'];
		if($description == '')
			$description = $bd_user_link['description'];
			
		/*gets adequate idUserLink id*/
		$user_link_id=$bd_user_link['idUserLink'];
		if($verbose == 1){ echo ("USER_LINK_ID: " . $user_link_id . '<br />');}
		
		if($verbose==1){echo ($shared."+".$description."+".$title.'<br />');}
		
		$query = $db->prepare("UPDATE User_Link SET 
		shared = :shared, description = :description, 
		title = :title WHERE idUserLink = :id_userLink;");
		$query->bindParam(":shared", $shared);
		$query->bindParam(":description", $description);
		$query->bindParam(":title", $title);
		$query->bindParam(":id_userLink", $user_link_id);
		$query->execute();
	}
	$stmt = $db->prepare('DELETE FROM User_Link_Tag WHERE idUserlink= :user_link_id');
	$stmt->bindParam(':user_link_id', $user_link_id);
	$stmt->execute();
	
	if($tag_list != ""){
		foreach ($tag_list as $tag) {
			/*inserts tags*/
			if($tag != '')
			{
				$tag=strtolower($tag);
				if($verbose == 1){ echo ("TAG:" . $tag . '<br />');}
				
				/*verifica se tag ja existe*/
				$stmt = $db->prepare('SELECT * FROM Tag WHERE tagName=:tag_name');
				$stmt->bindParam(':tag_name', $tag);
				$stmt->execute();
				$bd_tag = $stmt->fetch();
				if(!$bd_tag){/*tag still doesn't exist in the DB*/
					$stmt = $db->prepare('INSERT INTO Tag 
					values (NULL, :tag_name)');
					$stmt->bindParam(':tag_name', $tag);
					$stmt->execute();
				}/*if it exists already, we don't insert, only update variables in User_Link_Tag*/
				
				/*associates links to tags e utilizadores =) */
				if(!$bd_tag){/*if it was inserted earlier*/
					$tag_id = $db->query('SELECT max(idTag) 
					FROM Tag');
					$tag_id=$tag_id->fetch();
					$tag_id=$tag_id[0];
				}
				else{/*if it wasn't*/
					$tag_id=$bd_tag['idTag'];
					if($verbose == 1){ echo ("tag_id: " . $tag_id . '<br />');}
				}
				/*lastly, checking user_link_tag*/
				$query = $db->prepare("SELECT * FROM User_Link_Tag 
				WHERE idUserLink = :idUserLink AND idTag = :idTag");
				$query->bindParam(":idUserLink", $user_link_id);
				$query->bindParam(":idTag", $tag_id);
				$query->execute();
				$bd_user_link_tag = $query->fetch();
				
				if(! $bd_user_link_tag){
					$stmt = $db->prepare('insert into User_Link_Tag 
					values (:user_link_id, :tag_id)');
					$stmt->bindParam(':user_link_id', $user_link_id);
					$stmt->bindParam(':tag_id', $tag_id);
					$stmt->execute();
				}
			}
		}
	}
	if($verbose == 1){echo "adding link successful<br />";}
	/*testes*/
		if($verbose == 1){ echo "<br />test-link<br />idUser|userName|pass<br />";}
		$test1 = $db->query('SELECT * FROM Link');
		foreach ($test1 as $r) {
			if($verbose == 1){ echo ($r['idLink'] . " | " . $r['linkURL'] . " | "  . $r['hits'] . "<br />");}
		}
		if($verbose == 1){ echo "<br />test-tag<br />id|name<br />";}
		$test2 = $db->query('SELECT * FROM Tag');
		foreach ($test2 as $r) {
			if($verbose == 1){ echo ($r['idTag'] . " | " . $r['tagName'] . "<br />");}
		}
		
		if($verbose == 1){ echo "<br />test-user_link<br />idUserLink|idUser|idLink|shared|desc|title<br />";}
		$test2 = $db->query('SELECT * FROM User_Link');
		foreach ($test2 as $r) {
			if($verbose == 1){ echo ($r['idUserLink'] . " | " . $r['idUser']. " | ". $r['idLink']. " | ". $r['shared']. " | ". $r['description'] ." | " . $r['title']."<br />");}
		}
		
		if($verbose == 1){ echo "<br />test-user_link_tag<br />idUserLink|idTag<br />";}
		$test2 = $db->query('SELECT * FROM User_Link_Tag');
		foreach ($test2 as $r) {
			if($verbose == 1){ echo ($r['idUserLink'] . " | " . $r['idTag'] . "<br />");}
		}
	if($xml == 0){
		$error['Result'] = array('AddLink'=>'Success');
		echo json_encode($error);
		die;
	}
	else{
		$doc = new DomDocument('1.0');
		$doc->formatOutput = TRUE;
		// create root node
		$root = $doc->createElement('Result');
		$root = $doc->appendChild($root);
		$attr = $doc->createAttribute("xmlns:xsi");
		$attr->value = "http://www.w3.org/2001/XMLSchema-instance";
		$root->appendChild($attr);
		$attr = $doc->createAttribute("xsi:noNamespaceSchemaLocation");
		$attr->value = "http://gnomo.fe.up.pt/~ei10048/trabalho2/xsd.xsd";
		$root->appendChild($attr);
		//childs of root
		$error = $doc->createElement('AddLink');
		$error= $root->appendChild($error);
		$value = $doc->createTextNode('Success');
		$value = $error->appendChild($value);
		echo $doc->saveXML();
		die;
	}
?>